package org.example;

import java.io.File;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;

/**
 * https://blog.51cto.com/u_14555/6654511
 */
public class DateImage {
    public static void main(String[] args) throws Exception{
        File srcImage = new File("E:\\test\\img\\2024-06-01 094853 33.200000000,118.566000000.jpg");
        File destImage = new File("E:\\test\\img\\2.jpg");

        // 通过ImageIO和图像输入流设置imageReader
        Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName("JPG"); // 通过ImageIO获取imageReader迭代器
        ImageReader imageReader = iterator.next(); // 通过迭代器实例化ImageReader
        ImageInputStream imageInputStream = ImageIO.createImageInputStream(srcImage); // 通过ImageIO实例化图像输入流
        imageReader.setInput(imageInputStream, true);

        // 读取源图片IIOMetadata信息，存入IIOMetadata
        ImageReadParam imageReadParam = imageReader.getDefaultReadParam();
        IIOImage iioImage = imageReader.readAll(0, imageReadParam);
        IIOMetadata iioMetadata = iioImage.getMetadata();

        // 读取目标图片信息
        Iterator<ImageReader> iterator2 = ImageIO.getImageReadersByFormatName("JPG");
        ImageReader imageReader2 = iterator2.next();
        ImageInputStream imageInputStream2 = ImageIO.createImageInputStream(destImage);
        imageReader2.setInput(imageInputStream2, true);

        // 将源图片iioMetadata信息存入目标图片的IIOImage
        ImageReadParam imageReadParam2 = imageReader2.getDefaultReadParam();
        IIOImage iioImage2 = imageReader2.readAll(0, imageReadParam2);
        iioImage2.setMetadata(iioMetadata);

        // 将iioImage写入目标图片
        ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(destImage);
        Iterator<ImageWriter> iterator3 = ImageIO.getImageWritersByFormatName("JPG");
        ImageWriter imageWriter = iterator3.next();
        imageWriter.setOutput(imageOutputStream);
        imageWriter.write(iioImage2);

        //关闭流
        imageInputStream.close();
        imageOutputStream.close();

    }
}
